package com.bosc.automationui.service;

import com.bosc.automationui.constant.ConstantKey;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.management.relation.Role;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<Role> roles = new ArrayList<>();
        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();

        User user = new User("admin",
                "123456",
                true,
                true,
                true,
                true,
                grantedAuthorities);

        return user;
    }

    public void login(String username, String password, HttpServletResponse response) {
        if (username.equals("admin") && password.equals("abcd1234")) {
//                    List<User> roleList = new ArrayList<>();
            String subject = username + "-Udrt";
            Date expiredDate = new Date(System.currentTimeMillis() + 60 * 60 * 1000 * 12); // 12 hours
            String token = Jwts.builder()
                    .setSubject(subject)
                    .setExpiration(expiredDate) // 设置过期时间 365 * 24 * 60 * 60秒(这里为了方便测试，所以设置了1年的过期时间，实际项目需要根据自己的情况修改)
                    .signWith(SignatureAlgorithm.HS512, ConstantKey.SECRET_KEY) //采用什么算法是可以自己选择的，不一定非要采用HS512
                    .compact();
            // 登录成功后，返回token到header里面
            System.out.println("/login -> expiredDate = " + expiredDate + ", origin token = " + token);
            response.addHeader("Authorization", "Bearer " + token);
            response.addHeader("Access-Control-Expose-Headers", "Authorization");
        }
    }
}
